package com.itheima.utils;

import java.sql.*;

public class HiveUtil {
    private String jdbcUrl;
    private String username;
    private String password;
    private Connection connection;

    public HiveUtil() {
        this.jdbcUrl = "jdbc:hive2://node1:10000/ods";
        this.username = "hadoop";
        this.password = "";
    }

    // 获取数据库连接
    private Connection getConnection() throws SQLException {
        if (connection == null || connection.isClosed()) {
            try {
                Class.forName("com.mysql.cj.jdbc.Driver"); // 注册JDBC驱动程序
                connection = DriverManager.getConnection(jdbcUrl, username, password);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                throw new SQLException("JDBC driver not found", e);
            }
        }
        return connection;
    }

    // 执行查询并返回结果集
    public ResultSet executeQuery(String sql) {
        try{
            Connection conn = getConnection();
            PreparedStatement statement = conn.prepareStatement(sql);
            return statement.executeQuery();
        }catch(SQLException e){
            e.printStackTrace();
        }
        return null;
    }

    // 关闭数据库连接
    public void close() {
        try {
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
